//
//  PZTipsAlertView.m
//  PeiZiWangBei
//
//  Created by LK-IOS on 2017/11/1.
//  Copyright © 2017年 LK-IOS. All rights reserved.
//

#import "PZTipsAlertView.h"

#import  <objc/runtime.h>

//线条默认颜色

#define PZAlertViewLineColor [UIColor colorWithHexString:@"bfbfbf"]



@interface PZAlertButton()


@property (nonatomic, strong) CALayer *horizontalLine;//水平线
@property (nonatomic, strong) CALayer *verticalLine;//垂直线

@property (nonatomic, copy) void (^buttonClickedBlock)(PZAlertButton *alertButton);

@end

@implementation PZAlertButton


+ (instancetype)buttonWithTitle:(NSString *)title handler:(void (^)(PZAlertButton * _Nonnull))handler
{
    return [[self alloc] initWithTitle:title handler:handler];
}

- (instancetype)initWithTitle:(NSString *)title handler:(void (^)(PZAlertButton * _Nonnull))handler
{
    if (self = [super init]) {
        self.buttonClickedBlock = handler;
        
        self.titleLabel.font = [UIFont systemFontOfSize:16];//
        self.titleLabel.adjustsFontSizeToFitWidth = YES;//设置按钮字体之后，字体可调
       // [self setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
       // [self setTitleColor:[UIColor darkGrayColor] forState:UIControlStateHighlighted];
        [self setTitle:title forState:UIControlStateNormal];
        [self addTarget:self action:@selector(handlerClicked) forControlEvents:UIControlEventTouchUpInside];
        self.layer.cornerRadius = 4;
        self.layer.borderColor = [UIColor colorWithHexString:Orange].CGColor;
        self.layer.borderWidth = 1;
        self.clipsToBounds = YES;
        
//        _horizontalLine = [CALayer layer];
//        _horizontalLine.backgroundColor = PZAlertViewLineColor.CGColor;
//        [self.layer addSublayer:_horizontalLine];
//
//        _verticalLine = [CALayer layer];
//        _verticalLine.backgroundColor = PZAlertViewLineColor.CGColor;
//        _verticalLine.hidden = YES;
//        [self.layer addSublayer:_verticalLine];
        
        
        
    }
    return self;
}

- (void)handlerClicked
{
    if (self && self.buttonClickedBlock) self.buttonClickedBlock(self);
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    CGFloat lineWidth = self.lineWidth > 0 ? self.lineWidth : 1 / [UIScreen mainScreen].scale;
    _horizontalLine.frame = CGRectMake(0, 0, self.width, lineWidth);
    _verticalLine.frame = CGRectMake(0, 0, lineWidth, self.height);
}

- (void)setLineColor:(UIColor *)lineColor
{
    _lineColor = lineColor;
    _verticalLine.backgroundColor = lineColor.CGColor;
    _horizontalLine.backgroundColor = lineColor.CGColor;
}

@end

@interface PZTipsAlertView ()
{
    CGSize  _contentSize;
    CGFloat _paddingTop, _paddingBottom, _paddingLeft; // paddingRight = paddingLeft
    CGFloat _spacing;
}
@property (nonatomic, strong) NSMutableSet *subActions;
@property (nonatomic, strong) NSMutableSet *adjoinActions;

@end

static void *SnailAlertViewActionKey = &SnailAlertViewActionKey;

@implementation PZTipsAlertView

- (instancetype)initWithTitle:(NSString *)title message:(NSString *)message constantWidth:(CGFloat)constantWidth
{
    if (self = [super init]) {
        self.backgroundColor = [UIColor whiteColor];
        self.layer.cornerRadius = 10;
        self.clipsToBounds = NO;
        self.subOverflyButtonHeight = 42;
        
        _contentSize.width = 200; // default width = 200
        if (constantWidth > 0) _contentSize.width = constantWidth;
        _paddingTop = 15;
        _paddingBottom = 15;
        _paddingLeft = 20;
        _spacing = 15;
        
        if (title.length) {
            _titleLabel = [[UILabel alloc] init];
            _titleLabel.text = title;
            _titleLabel.numberOfLines = 0;
            _titleLabel.textAlignment = NSTextAlignmentCenter;
            _titleLabel.font = [UIFont systemFontOfSize:20];
            [self addSubview:_titleLabel];
            
            _titleLabel.size = [_titleLabel sizeThatFits:CGSizeMake(_contentSize.width-2*_paddingLeft, MAXFLOAT)];
            _titleLabel.y = _paddingTop;
            _titleLabel.centerX = _contentSize.width / 2;
            _contentSize.height = _titleLabel.bottom;
            
            _line = [UILabel new];
            _line.backgroundColor = NumberColor(236, 236, 236);
            
            [self addSubview:_line];
            _line.frame = CGRectMake(rate375(22),46, (_contentSize.width - 2*rate375(22)), 1);
          
           _contentSize.height = _line.bottom;
        }
        
        if (message.length) {
            _messageLabel = [[UILabel alloc] init];
            _messageLabel.numberOfLines = 0;
            _messageLabel.font = [UIFont systemFontOfSize:14];
            _messageLabel.textColor = [UIColor colorWithHexString:battleshipGrey];
           
            [self addSubview:_messageLabel];

            NSAttributedString *string = [NSString createAttriStringWithString:message andSpace:2.0 Font:[UIFont systemFontOfSize:14]];
            _messageLabel.attributedText = string;
            
           // _messageLabel.size = [_messageLabel sizeThatFits:CGSizeMake(_contentSize.width - 2*_paddingLeft, MAXFLOAT)];
            
            CGFloat Height =   [NSString getHeightWithText:message font:[UIFont systemFontOfSize:16] MaxWidth:_contentSize.width - 2*_paddingLeft lineSpace:2];
            
            
            if (Height < 22) {
                //一行文字居中显示
                _messageLabel.textAlignment = NSTextAlignmentCenter;
            }else
            {
                //多行左对齐
                _messageLabel.textAlignment = NSTextAlignmentLeft;
            }
            
            
            if (Height < 64) {
                //内容自适应高度 默认最低60
                Height = 64;
            }
           
            
            _messageLabel.size = CGSizeMake(_contentSize.width - 2*_paddingLeft, Height);
            
            _messageLabel.y = _line.bottom + _spacing;
            _messageLabel.centerX = _contentSize.width / 2;
            
            _contentSize.height = _messageLabel.bottom;
        }
        
        self.size = CGSizeMake(_contentSize.width, _contentSize.height + _paddingBottom);
        if (!title.length && !message.length) {
            self.size = CGSizeZero;
        }
    }
    return self;
}

static void *zhAlertViewActionKey = &zhAlertViewActionKey;

- (void)addAction:(PZAlertButton *)action
{
    [self clearActions:self.adjoinActions.allObjects];
    [self.adjoinActions removeAllObjects];
    
    void (^layout)(CGFloat) = ^(CGFloat top){
        CGFloat width = _contentSize.width - action.edgeInsets.left - action.edgeInsets.right;
        action.size = CGSizeMake(width, self.subOverflyButtonHeight);
        action.y = top;
        action.centerX = _contentSize.width / 2;
    };
    
    PZAlertButton *lastAction = objc_getAssociatedObject(self, zhAlertViewActionKey);
    if (lastAction) { // current
        if (![action isEqual:lastAction]) layout(lastAction.bottom + action.edgeInsets.top);
    } else { // first
        layout(_contentSize.height + action.edgeInsets.top + 10); // 增加10间距
    }
    
    action.verticalLine.hidden = YES;
    [self insertSubview:action atIndex:0];
    self.size = CGSizeMake(_contentSize.width, action.bottom + action.edgeInsets.bottom);
    objc_setAssociatedObject(self, zhAlertViewActionKey, action, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void)adjoinWithLeftAction:(PZAlertButton *)leftAction rightAction:(PZAlertButton *)rightAction
{
    [self clearActions:self.subviews];
    objc_setAssociatedObject(self, zhAlertViewActionKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
    leftAction.size = CGSizeMake((_contentSize.width - rate375(58)) / 2, self.subOverflyButtonHeight);
    leftAction.y = _contentSize.height + leftAction.edgeInsets.top;
    leftAction.x = rate375(22);
    
    rightAction.frame = leftAction.frame;
    rightAction.x = leftAction.right + rate375(14);
    rightAction.verticalLine.hidden = NO;
    [self addSubview:leftAction];
    [self addSubview:rightAction];
    self.adjoinActions = [NSMutableSet setWithObjects:leftAction, rightAction, nil];
    self.size = CGSizeMake(_contentSize.width, leftAction.bottom + 20);
}

- (void)clearActions:(NSArray *)subviews
{
    for (UIView *subview in subviews) {
        if ([subview isKindOfClass:[PZAlertButton class]]) {
            [subview removeFromSuperview];
        }
    }
}

@end
